<?php

namespace App\Http\Controllers\BK;

use App\Http\Controllers\Controller;
use App\Http\Requests\BK\Auth\LoginRequest;
use App\Models\Admin;
use Earnp\GoogleAuthenticator\Facades\GoogleAuthenticator;
use Illuminate\Http\Response;

class AuthController extends Controller
{
    public function __construct()
    {
        $this->middleware(['auth:admins'])->except(['login','getCode']);
    }

    public function login(LoginRequest $request)
    {
        if (!captcha_api_check($request->get('captcha'), $request->get('key'))) {
            return error('验证码错误', 422,422);
        }
        $credentials = [
            'account'=>$request->get('account'),
            'password'=>$request->get('password'),
            'status' => Admin::STATUS_ENABLE,
        ];
        if (! $token = auth('admins')->attempt($credentials)) {
            return error('账号或密码不正确',401,401);
        }
        $admin = auth('admins')->authenticate($token);
        $googleSecret  = $admin->google_secret;
        if(!empty($googleSecret)){
            $check = GoogleAuthenticator::CheckCode($googleSecret,$request->get('google_code'));
            if(!$check){
                return error('谷歌验证码不正确',401,401);
            }
        }
        $tokenData = [
            'access_token' => $token
        ];
        return success(null,'登录成功',Response::HTTP_OK,$tokenData);
    }

    public function logout()
    {
        auth('admins')->logout();
        return success();
    }

    public function getCode()
    {
        $data = [
            'url' => app('captcha')->create('default', true)
        ];
        return success($data);
    }
}
